<template>
  <el-drawer
    :visible.sync="drawerVisible"
    :wrapper-closable="false"
    :close-on-press-escape="false"
    :with-header="false"
    :append-to-body="true"
    size="760px"
    @close="handleClose"
  >
    <div class="filter-dialog-main">
      <SectionTitle title="前置条件" style="margin-bottom: 8px">
        <span class="title-tip">满足设置的前置条件时才触发校验规则</span>
      </SectionTitle>
      <el-form :model="targetData" class="top-content" label-position="top">
        <el-form-item class="top-content-rule" prop="frontRole">
          <div slot="label" class="top-title">规则类型</div>
          <selectWithoutHttp v-model="targetData.frontRole" :list-data="ruleOptions" class="width100" />
        </el-form-item>
      </el-form>
      <div class="filter-scroll">
        <div
          v-for="(item, index) in targetData.frontFilterList"
          :key="index"
          :class="{'last': targetData.frontFilterList.length - 1 === index}"
          class="filter-item">
          <FilterValue
            :filter-item="item"
            :field-list="fieldList"
            :is-show-status="false"
            has-value-type
            key-name="filterField" />
          <div class="btn-list">
            <img :src="copyGroupIcon" class="copy-icon" alt="" @click="copyItem(item, 'frontFilterList')">
            <img :src="deleteGroupIcon" class="delete-icon" alt="" @click="deleteItem(index, 'frontFilterList')">
          </div>
        </div>
      </div>
      <div :style="!targetData.frontFilterList || targetData.frontFilterList.length ===0?{marginTop: 0}:''" style="margin-bottom: 32px" class="footer-bar">
        <div class="add-btn" @click="addFilter('frontFilterList')">添加条件 <i class="add-icon el-icon-plus" /></div>
        <div class="tip">最多添加20条</div>
      </div>
      <SectionTitle title="校验规则" style="margin-bottom: 8px">
        <el-tooltip placement="top">
          <div slot="content" style="line-height: 1.5;">
            <div>填写符合提示，按符合的逻辑判断弹窗提示；</div>
            <div>填写不符合提示，按不符合的逻辑判断弹窗提示。</div>
          </div>
          <tipIcon is-diy style="margin-left: 4px"/>
        </el-tooltip>
      </SectionTitle>
      <div class="pr24">
        <el-form ref="filterRef" :model="targetData" :rules="rules" class="top-content" label-position="top">
          <el-form-item class="top-content-rule" prop="role">
            <div slot="label" class="top-title">规则类型</div>
            <selectWithoutHttp v-model="targetData.role" :list-data="ruleOptions" class="width100" />
          </el-form-item>
          <el-form-item prop="accordName" class="top-content-right">
            <div slot="label" class="top-title">符合时弹窗提示</div>
            <el-input
              v-model="targetData.accordName"
              :maxlength="200"
              :disabled="!!targetData.name"
              class="width100"
              placeholder="请输入提示"
              size="small"
              @blur="resetValidate('name')"
            />
          </el-form-item>
          <el-form-item prop="name" class="top-content-right">
            <div slot="label" class="top-title">不符合时弹窗提示</div>
            <el-input
              v-model="targetData.name"
              :maxlength="200"
              :disabled="!!targetData.accordName"
              class="width100"
              placeholder="请输入提示"
              size="small"
              @blur="resetValidate('accordName')"
            />
          </el-form-item>
        </el-form>
      </div>
      <div class="filter-scroll">
        <div
          v-for="(item, index) in targetData.filterList"
          :key="index"
          :class="{'last': targetData.filterList.length - 1 === index}"
          class="filter-item">
          <FilterValue
            :filter-item="item"
            :field-list="fieldList"
            :is-show-status="false"
            has-value-type
            key-name="filterField" />
          <div class="btn-list">
            <img :src="copyGroupIcon" class="copy-icon" alt="" @click="copyItem(item)">
            <img :src="deleteGroupIcon" class="delete-icon" alt="" @click="deleteItem(index)">
          </div>
        </div>
      </div>
      <div :style="!targetData.filterList || targetData.filterList.length ===0?{marginTop: 0}:''" class="footer-bar">
        <div class="add-btn" @click="addFilter()">添加规则 <i class="add-icon el-icon-plus" /></div>
        <div class="tip">最多添加20条</div>
      </div>
      <div class="btn">
        <el-button type="primary" size="small" @click="toSubmit()">保存</el-button>
        <el-button type="info" size="small" class="cancel-btn-style" @click="handleClose">取消</el-button>
        <el-checkbox v-model="targetData.realTime" class="checkbox">开启表单填写实时验证</el-checkbox>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import SectionTitle from '@/components/Title';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import deleteGroupIcon from '@/assets/legalProcess/deleteIcon.png';
import copyGroupIcon from '@/assets/legalProcess/copyIcon.png';
import FilterValue from '../../../filterValue';
import ElMessage from '@/utils/message';
export default {
  name: 'FilterDialog',
  components: { SectionTitle, selectWithoutHttp, FilterValue },
  props: {
    fieldList: {
      type: Array,
      default: () => ([])
    },
    allFieldList: {
      type: Array,
      default: () => ([])
    },
    fieldCondition: {
      type: Array,
      default: () => ([])
    }
  },
  data() {
    const validateName = (msg, key) => {
      return (rule, value, callback) => {
        const name = this.targetData[key];
        if ((Array.isArray(name) && name.length > 0) || (!Array.isArray(name) && (name || name === 0))) {
          callback();
        } else {
          callback(new Error(msg));
        }
      };
    };
    const validateDesc = (msg) => {
      return (rule, value, callback) => {
        if (this.targetData.name || this.targetData.accordName) {
          callback();
        } else {
          callback(new Error(msg));
        }
      };
    };
    return {
      deleteGroupIcon, copyGroupIcon,
      ruleOptions: [{ id: 0, value: '符合以下全部条件' }, { id: 1, value: '符合以下任一条件' }],
      drawerVisible: false,
      editIndex: -1,
      targetData: {
        frontRole: 0,
        role: 0,
        accordName: '',
        frontFilterList: [],
        filterList: []
      },
      rules: {
        role: [{ required: true, trigger: 'change', validator: validateName('请选择规则类型', 'role') }],
        name: [{ required: true, trigger: 'change', validator: validateDesc('请输入提示') }],
        accordName: [{ required: true, trigger: 'change', validator: validateDesc('请输入提示') }]
      }
    };
  },
  methods: {
    addFilter(key = 'filterList') {
      if (!this.targetData[key]) this.$set(this.targetData, key, []);
      if (this.targetData[key].length >= 20) {
        ElMessage.warning('最多添加20条规则');
        return;
      }
      this.targetData[key].push({
        filterField: '',
        math: '=',
        valueType: 0, //  0:值  1:字段
        value: ''
      });
      this.$forceUpdate();
    },
    resetValidate(resetKey) {
      this.$nextTick(() => {
        this.$refs['filterRef'] && this.$refs['filterRef'].clearValidate([resetKey]);
      });
    },
    copyItem(item, key = 'filterList') {
      if (this.targetData[key].length >= 20) {
        ElMessage.warning('最多添加20条规则');
        return;
      }
      this.targetData[key].push(_.cloneDeep(item));
    },
    deleteItem(index, key = 'filterList') {
      this.targetData[key].splice(index, 1);
    },
    openDialog(editIndex, data) {
      if (data) {
        this.editIndex = editIndex;
        this.targetData = _.cloneDeep(data);
        if (!this.targetData.realTime) this.$set(this.targetData, 'realTime', false);
      } else {
        this.$set(this.targetData, 'name', '');
        this.$set(this.targetData, 'realTime', false);
        this.$set(this.targetData, 'role', 0);
        this.$set(this.targetData, 'frontRole', 0);
      }
      this.drawerVisible = true;
      this.$nextTick(() => {
        if (this.$refs.filterRef) this.$refs.filterRef.clearValidate();
      });
    },
    handleClose() {
      this.drawerVisible = false;
      this.editIndex = -1;
      this.targetData = {};
    },
    toSubmit() {
      this.targetData.filterList = (this.targetData.filterList || []).filter(i => !!i.filterField);
      this.targetData.frontFilterList = (this.targetData.frontFilterList || []).filter(i => !!i.filterField);
      this.$refs.filterRef.validate(valid => {
        if (valid) {
          this.$emit('submit', this.editIndex, this.targetData);
          this.handleClose();
        } else {
          ElMessage.error('请检查信息是否填写完整');
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.filter-dialog-main {
  padding: 24px 0px 12px 24px;
  .title-tip {
    font-size: 14px;
    color: #999;
    font-weight: normal;
    margin-left: 6px;
  }
}
.pr24 {
  padding-right: 24px;
}
.top-content {
  display: flex;
  border-bottom: 1px solid #EBEEFD;
  padding-bottom: 20px;
  margin-bottom: 20px;
  &::v-deep {
    .el-form-item__label {
      padding-bottom: 0;
      &::before {
        display: none;
      }
    }
  }
  .top-title {
    font-size: 14px;
    color: #666;
    // margin-bottom: 5px;
    display: flex;
    .tip {
      color: #999;
    }
  }
  .top-content-right {
    margin-left: 10px;
    flex:1;
    margin-bottom: 0;
  }
  .top-content-rule {
    margin-bottom: 0;
    flex-basis: 180px;
  }
  .width100 {
    width: 100%;
    &::v-deep {
      .el-select,.el-input,.el-input__inner {
        width: 100%;
      }
    }
  }
}
.footer-bar {
  display: flex;
  align-items: center;
  margin-top: 16px;
  .add-btn {
    font-size: 14px;
    color: #406eff;
    cursor: pointer;
    margin-right: 12px;
    font-weight: bold;
    .add-icon {
      font-size: 12px;
    }
  }
  .tip {
    font-size: 12px;
    color: #999;
  }
}
.btn {
  display: flex;
  margin-top: 20px;
  align-items: center;
  .checkbox {
    margin-left: 12px;
  }
}
.btn-list {
  display: flex;
  align-items: center;
}
.delete-icon {
  width: 12px;
  cursor: pointer;
  margin-left: 9px;
}
.copy-icon {
  width: 12px;
  cursor: pointer;
  margin-left: 9px;
}
.filter-item {
  display: flex;
  margin-bottom: 25px;
  &.last {
    margin-bottom: 0;
  }
  &::v-deep {
    .select-field {
      width: 160px !important;
      .el-input__inner {
        width: 160px !important;
      }
    }
    .select-math {
      width: 120px !important;
      .el-input__inner {
        width: 120px !important;
      }
    }
  }
}
.filter-scroll {
  max-height: calc((100vh - 460px) / 2);
  @include scrollBar($x: hidden, $y: auto);
}
</style>
<style lang="scss">
.dropdown-no-hover {
  .el-select-dropdown__item {
    background-color: #fff !important;
  }
}
</style>
